package com.example.testapp.ui.home

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import android.os.Build
import android.graphics.Bitmap
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.testapp.R
import com.example.testapp.databinding.FragmentHomeBinding
import com.google.android.material.bottomsheet.BottomSheetDialog

class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!
    private lateinit var homeViewModel: HomeViewModel
    
    companion object {
        private const val TAG = "HomeFragment"
    }

    // 添加相机权限请求
    private val requestPermissionLauncher: ActivityResultLauncher<String> =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            if (isGranted) {
                // 权限获取成功，启动相机
                launchCamera()
            } else {
                // 权限被拒绝，检查是否应该显示权限说明
                if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
                    // 用户拒绝了权限，但没有选择"不再询问"，显示解释对话框
                    showPermissionExplanationDialog()
                } else {
                    // 用户选择了"不再询问"，引导用户去设置页面开启权限
                    showSettingsDialog()
                }
            }
        }

    // 添加存储权限请求
    private val requestStoragePermissionLauncher: ActivityResultLauncher<String> =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            if (isGranted) {
                // 权限获取成功，打开相册
                openGallery()
            } else {
                // 显示权限说明
                showStoragePermissionDialog()
            }
        }

    // 添加相机启动器
    private val cameraLauncher: ActivityResultLauncher<Intent> =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                // 照片拍摄成功，处理照片
                val extras = result.data?.extras
                val imageBitmap = extras?.get("data") as? Bitmap
                if (imageBitmap != null) {
                    handleImageData(imageBitmap, null)
                }
            }
        }

    // 添加相册选择启动器
    private val galleryLauncher: ActivityResultLauncher<Intent> =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == Activity.RESULT_OK) {
                val selectedImage = result.data?.data
                if (selectedImage != null) {
                    // 处理选择的图片
                    handleImageData(null, selectedImage)
                }
            }
        }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        val root: View = binding.root

        // 设置相机按钮点击事件，显示底部选择框
        binding.cameraButton.setOnClickListener { showImagePickerDialog() }

        return root
    }

    private fun showImagePickerDialog() {
        val dialog = BottomSheetDialog(requireContext())
        val dialogView = layoutInflater.inflate(R.layout.dialog_image_picker, null)

        dialogView.findViewById<View>(R.id.btn_take_photo).setOnClickListener {
            dialog.dismiss()
            checkAndRequestCameraPermission()
        }

        dialogView.findViewById<View>(R.id.btn_pick_gallery).setOnClickListener {
            dialog.dismiss()
            checkAndRequestStoragePermission()
        }

        dialog.setContentView(dialogView)
        dialog.show()
    }

    private fun checkAndRequestStoragePermission() {
        val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Manifest.permission.READ_MEDIA_IMAGES
        } else {
            Manifest.permission.READ_EXTERNAL_STORAGE
        }

        if (ContextCompat.checkSelfPermission(requireContext(), permission) ==
            PackageManager.PERMISSION_GRANTED
        ) {
            openGallery()
        } else {
            requestStoragePermissionLauncher.launch(permission)
        }
    }

    private fun showStoragePermissionDialog() {
        AlertDialog.Builder(requireContext())
            .setTitle("需要存储权限")
            .setMessage("我们需要访问存储权限来选择小票照片。")
            .setPositiveButton("去设置") { _, _ ->
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                val uri = Uri.fromParts("package", requireActivity().packageName, null)
                intent.data = uri
                startActivity(intent)
            }
            .setNegativeButton("取消", null)
            .create()
            .show()
    }

    private fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK)
        intent.type = "image/*"
        galleryLauncher.launch(intent)
    }

    private fun checkAndRequestCameraPermission() {
        if (ContextCompat.checkSelfPermission(
                requireContext(), Manifest.permission.CAMERA
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            // 已经有权限，直接启动相机
            launchCamera()
        } else {
            // 请求权限
            requestPermissionLauncher.launch(Manifest.permission.CAMERA)
        }
    }

    private fun showPermissionExplanationDialog() {
        AlertDialog.Builder(requireContext())
            .setTitle("需要相机权限")
            .setMessage("为了能够拍摄小票照片，我们需要使用您的相机。请在接下来的对话框中授予相机权限。")
            .setPositiveButton("确定") { _, _ ->
                // 再次请求权限
                requestPermissionLauncher.launch(Manifest.permission.CAMERA)
            }
            .setNegativeButton("取消", null)
            .create()
            .show()
    }

    private fun showSettingsDialog() {
        AlertDialog.Builder(requireContext())
            .setTitle("需要相机权限")
            .setMessage("我们需要相机权限来拍摄小票照片。请在设置中开启相机权限。")
            .setPositiveButton("去设置") { _, _ ->
                // 打开应用设置页面
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                val uri = Uri.fromParts("package", requireActivity().packageName, null)
                intent.data = uri
                startActivity(intent)
            }
            .setNegativeButton("取消", null)
            .create()
            .show()
    }

    private fun launchCamera() {
        try {
            val takePictureIntent = Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
            cameraLauncher.launch(takePictureIntent)
        } catch (e: Exception) {
            Toast.makeText(
                requireContext(),
                "无法启动相机，请确认您的设备有相机功能",
                Toast.LENGTH_SHORT
            ).show()
        }
    }

    /**
     * 处理图片数据
     * @param bitmap 相机拍照返回的位图数据
     * @param uri 相册选择返回的图片URI
     */
    private fun handleImageData(bitmap: Bitmap?, uri: Uri?) {
        val info = StringBuilder()
        val title: String

        if (bitmap != null) {
            // 处理相机返回的图片
            title = "拍照图片信息"
            info.append("图片类型：相机拍摄\n\n")
            info.append("图片宽度：${bitmap.width} px\n")
            info.append("图片高度：${bitmap.height} px\n")
            val sizeInMB = bitmap.byteCount / (1024f * 1024f)
            info.append("图片大小：%.2f MB\n".format(sizeInMB))
            info.append("图片格式：${if (bitmap.hasAlpha()) "RGBA_8888" else "RGB_565"}\n")
            info.append("像素总数：${bitmap.width * bitmap.height}\n")
            
            // 记录日志
            Log.d(TAG, "处理相机拍摄的图片")
            Log.d(TAG, info.toString())
        } else if (uri != null) {
            // 处理相册选择的图片
            title = "相册图片信息"
            info.append("图片类型：相册选择\n\n")
            info.append("图片URI：${uri}\n")
            info.append("图片路径：${uri.path}\n")
            val fileName = uri.lastPathSegment
            info.append("文件名：$fileName\n")
            
            // 尝试获取文件MIME类型
            val mimeType = requireContext().contentResolver.getType(uri)
            if (mimeType != null) {
                info.append("文件类型：$mimeType\n")
            }

            // 记录日志
            Log.d(TAG, "处理相册选择的图片")
            Log.d(TAG, info.toString())
        } else {
            return
        }

        // 使用AlertDialog展示图片信息
        val builder = AlertDialog.Builder(requireContext())
            .setTitle(title)
            .setMessage(info.toString())
            .setPositiveButton("确定") { _, _ ->
                // TODO: 这里可以添加后续的处理逻辑
                Toast.makeText(requireContext(), "准备处理图片...", Toast.LENGTH_SHORT).show()
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
            }

        // 创建并显示对话框
        val dialog = builder.create()
        dialog.show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 